package com.toycloud.common.utils;

import com.alibaba.fastjson2.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StringToNestedListTypeHandler extends BaseTypeHandler<List<List<String>>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<List<String>> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List<List<String>> 转换为 JSON 字符串
        String jsonString = JSON.toJSONString(parameter);
        ps.setString(i, jsonString);
    }

    @Override
    public List<List<String>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJsonToNestedList(json);
    }

    @Override
    public List<List<String>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJsonToNestedList(json);
    }

    @Override
    public List<List<String>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJsonToNestedList(json);
    }

    private List<List<String>> parseJsonToNestedList(String json) {
        if (json == null || json.isEmpty()) {
            return new ArrayList<>();
        }
        // 使用 JSON 解析字符串为 List<List<String>>
        return JSON.parseObject(json, new ArrayList<List<String>>(){}.getClass().getGenericSuperclass());
    }
}


